
#include "CThreadPool.h"
#include "CWorkerThread.h"
#include "pthread.h"

CWorkerThread::CWorkerThread(bool bDetach):CThread(bDetach)
{
  m_Job = NULL;
  m_JobData = NULL;
  m_ThreadPool = NULL;
  //m_IsEnd = false;
  m_lpJobSem = new CThreadSem(0);
}

CWorkerThread::~CWorkerThread()
{
	delete m_lpJobSem;
  if(m_Job != NULL)
    delete m_Job;
  if(m_JobData != NULL)
  	m_JobData = NULL;
}

void CWorkerThread::Run()
{
  //pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock, m_WorkMutex.GetThdMutex());
  for(;;)
  {
  	//printf("Worker Thread running[%d]\n", pthread_self());
    while(m_Job == NULL)
    {
      m_lpJobSem->SemWait();
      pthread_testcancel();
    }
    //printf("WorkerThread::Run[%d]\n", pthread_self());
    m_Job->Run(m_JobData);
    m_Job->SetSevice(NULL);
    m_Job->SetWorkThread(NULL);
    if(m_Job != NULL)
    {
      delete m_Job;
      m_Job = NULL;
    }
    
    m_JobData = NULL;
    
    m_ThreadPool->MoveToIdleList(this);
  }
  //pthread_cleanup_pop(0);
}

void CWorkerThread::SetJob(CJob* job, void* jobdata)
{
  //m_varMutex.Lock();
  m_Job = job;
  m_JobData = jobdata;
  job->SetWorkThread(this);
  m_lpJobSem->SemPost();
}

void CWorkerThread::SetThreadPool(CThreadPool* thrpool)
{
  //m_varMutex.Lock();
  m_ThreadPool = thrpool;
  //m_varMutex.Unlock();
}